package com.qf.fmall.user.controller;

import com.qf.fmall.user.entity.User;
import com.qf.fmall.user.service.IUserService;
import com.qf.fmall.user.vo.LoginVo;
import com.qf.fmall.user.vo.RegisterVo;
import com.qf.fmall.utils.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wbw
 * @since 2023-11-27
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
@Slf4j //打印日志的注解，lombok提供
public class UserController {
    /**
     * 获取post请求体中的json
     *{“username":"luffy003”,"password":"123456","repassword":"123456"}
     * @return
     * 用户注册
     */
    @Autowired
    private IUserService userService;
    @RequestMapping("/regist")
    public ResultVo regist(@RequestBody RegisterVo registerVo){
        //1.打印日志，把该接口接收到的参数打印出来
        log.info("用户注册接口接收到的数据为：username={},password={},repassword={}",registerVo.getUsername(),registerVo.getPassword(),registerVo.getRepassword());
        //2.进行需要的参数校验
        if (!registerVo.getPassword().equals(registerVo.getRepassword())) {
          return  ResultVo.notok(-10001,"密码不一致");
        }
        //调用service层的对象进行业务处理
       boolean flag = userService.regist(registerVo);
        if (flag){
//            result.put("code",10000);
//            result.put("msg","ok");
           return ResultVo.ok(10000,"ok");
        }else {
//            result.put("code","-10002");
//            result.put("msg","注册失败");
           return ResultVo.notok(-10002,"注册失败");
        }
    }

    @GetMapping("/login")
    public ResultVo login(String username,String password){
        //1.打印接收参数日志
        log.info("登陆接口收到的参数,username={},password={}",username,password);
        //2.校验参数合法性
        if (username==null||username.equals("")){
            throw new RuntimeException("用户名不合法");
        }
        if (password==null||password.equals("")){
            throw new RuntimeException("密码不能为空");
        }
        //3.调用service层对象处理业务逻辑
        LoginVo loginVo = userService.login(username,password);
        //4.返回json
        if (loginVo.getStatus()){
           return ResultVo.ok(10000,loginVo.getToken(),loginVo.getUser());
        }else {
            return ResultVo.notok(-10001,"login error");
        }
    }
}
